import os
import sys
import time
import ResultToFeishu


user_name = os.environ.get('username')
project_name = os.environ.get('PROJECT_NAME')
company_name = os.environ.get('COMPANY_NAME')
pack_name = os.environ.get('PACK_NAME')
bundle_version_code = os.environ.get('BUNDLE_VERSIONCODE')
min_sdk_version = os.environ.get('MIN_SDK_VERSION')
target_sdk_version = os.environ.get('TARGET_SDK_VERSION')
version = os.environ.get('VERSION')
out_path = os.environ.get('OUT_PATH')



# 设置你本地的Unity安装目录
unity_exe = 'D:/Unity Editor/Editor/Unity.exe'
# unity工程目录，当前脚本放在unity工程根目录中
project_path = 'D:/UnityProjects/lcmclient Android/Teran'
# 日志
log_file = os.getcwd() + '/unity_log.log'
static_func = 'BuildMgr.BuildAndroid'
android_sdk = "E:/Android/SDK/android-sdk-windows"
android_ndk = "E:/Android/NDK/android-ndk-r13b"
 
# 杀掉unity进程
def kill_unity():
    os.system('taskkill /IM Unity.exe /F')
 
def clear_log():
    if os.path.exists(log_file):
        os.remove(log_file)
 
# 调用unity中我们封装的静态函数
def call_unity_static_func(func):
    kill_unity()
    time.sleep(1)
    clear_log()
    time.sleep(1)
    cmd = 'start %s -quit -batchmode -projectPath %s -androidSdkPath %s -androidNdkPath %s -logFile %s -executeMethod %s --PROJECT_NAME:%s --COMPANY_NAME:%s --PACK_NAME:%s --BUNDLE_VERSIONCODE:%s --MIN_SDK_VERSION:%s --TARGET_SDK_VERSION:%s --VERSION:%s --OUT_PATH:%s'\
        %(unity_exe,project_path,android_sdk,android_ndk,log_file,func\
        , project_name, company_name, pack_name, bundle_version_code, min_sdk_version, target_sdk_version, version, out_path)
    print('run cmd:  ' + cmd)
    os.system(cmd)
 
    
 
# 实时监测unity的log, 参数target_log是我们要监测的目标log, 如果检测到了, 则跳出while循环    
def monitor_unity_log(target_log):
    pos = 0
    while True:
        if os.path.exists(log_file):
            break
        else:
            time.sleep(0.1) 
    while True:
        fd = open(log_file, 'r', encoding='utf-8')
        if 0 != pos:
            fd.seek(pos, 0)
        while True:
            line = fd.readline()
            pos = pos + len(line)
            if target_log in line:
                print(u'监测到unity输出了目标log: ' + target_log)
                fd.close()
                return
            if line.strip():
                print(line)
            else:
                break
        fd.close()

if __name__ == '__main__':
    print("入口程序")
    os.system('echo "Hello World"')
    print("结束")
    raise Exception('错误')
    # status = jk.get_build_info(name=JenkinsResultToFeishu.job_name, number=JenkinsResultToFeishu.build_id)['result']
    # JenkinsResultToFeishu.SetBuildResultInfo(status)
    # JenkinsResultToFeishu.SendBuildEndMsg()